# -*- coding: UTF-8 -*-
# @Time : 2021/12/9 0009 15:32
# @Author : lyw
# @Remark : 精密空调server
import re
import time

from db.common.IOTManager.AirConditioner.air_conditioner import ACSelectDB, ACListDB, ACRetrieveDB
try:
    from opm_pyirm import GetStatusById
except ImportError:
    try:
        from bsmiddle import GetStatusById
    except ImportError:
        def GetStatusById(*args):
            return [1, 2]

from model.common.IOTManager.iot_base import SRoomIOTMiddleModel
from server.public.IOTManager.server_base import IOTBaseServer


class PrecisionACSelectServer(IOTBaseServer):
    __db__ = ACSelectDB
    __model__ = SRoomIOTMiddleModel
    search = "ac_name"

    def __init__(self):
        super().__init__()
        self.ac_temp = self.db.read_template()

    def device_info(self, device_list, state_dict: dict = None):
        """

        @return:
        """
        res_device_data = []
        if state_dict is None:
            state_dict = {"state": 1}
        if state_dict["state"] != 2:
            state_dict["state"] = 1
        for device_data in device_list:
            status = GetStatusById(device_data["code"])
            if isinstance(status ,int):
                status = status
            else:
                status = status[1]
            if state_dict is not None:
                if status != 1:
                    state_dict["state"] = 2
            info_data = {"name": device_data["mxlabel"], "code": device_data["code"],
                         "state": self.set_state(status),
                         "local": self.db.get_local(
                             self.model(device_type=self.db.device_type, iot_code=device_data["code"],
                                        sroom_code="")),
                         "alarm_info": "", "mxdevicetype": device_data["mxdevicetype"],
                         }
            # 获取告警信息
            self.alert_info(device_data, info_data)

            # 获取数据
            self.query_table_data(device_data, info_data)

            res_device_data.append(info_data)

        return res_device_data

    def query_table_data(self, device_data, info_data):
        """
         查找 table 告警数据
        @param info_data:
        @param device_data:
        @return:
        """
        # 当前的模板
        current_temp = self.ac_temp.get(device_data["mxdevicetype"].rsplit("\\", 1)[1])[
            "home_state"] if self.ac_temp.get(
            device_data["mxdevicetype"].rsplit("\\", 1)[1]) is not None else {}
        # 定义要取的参数

        res_query_field = [("result_temp", "回风温度"), ("result_humidity", "回风湿度"), ("result_temp", "设定温度"),
                           ("set_humidity", "设定湿度"), ("set_temp", "设定温度"), ("arefaction", "除湿"),
                           ("humidification", "加湿")]

        monitor_data_dict = {}
        for monitor_key, monitor_value in device_data["sub_monitor"].items():

            monitor_table_data = self.db.query_monitor_table_data(monitor_key)
            if monitor_table_data:
                monitor_data_dict[monitor_key.rsplit(".", 1)[1]] = monitor_table_data
        # 设置默认参数
        self.set_default(res_query_field, info_data)

        for query_field in res_query_field:
            if current_temp is None:
                continue
            for template in current_temp:
                if re.search(query_field[1], template["mxlabel"]):

                    if query_field[0] in ("result_temp", "result_humidity"):

                        info_data[query_field[0]] = {
                            "data": monitor_data_dict["%s_" % template["plugin"]][
                                template["key"]] if monitor_data_dict.get("%s_" % template["plugin"]) else "-",
                            "unit": template["mxunit"]}

                    else:
                        info_data[query_field[0]] = monitor_data_dict[template["plugin"]][
                            "key"] if monitor_data_dict.get(
                            template["plugin"]) else "-"

    @staticmethod
    def set_default(res_query_field, info_data):
        """
        设置默认值
        @param res_query_field:
        @param info_data:
        @return:
        """
        for query_field in res_query_field:
            if query_field[0] in ("result_temp", "result_humidity"):
                info_data[query_field[0]] = {"data": "-", "unit": "-"}
            else:
                info_data[query_field[0]] = "-"


class ACListServer(PrecisionACSelectServer):
    __db__ = ACListDB

    def list(self):
        """
        获取设备列表
        @return:
        """
        dev_list = self.db.query_device()
        for device_data in dev_list:
            status = GetStatusById(device_data["code"])
            if isinstance(status ,int):
                status = status
            else:
                status = status[1]
            device_data["state"] = self.set_state(status)
        return dev_list


class ACRetrieveServer(PrecisionACSelectServer):
    __db__ = ACRetrieveDB

    def retrieve(self, code):
        """
        获取设备信息
        @param code:
        @return:
        """
        device_data = self.db.retrieve(code)
        status = GetStatusById(device_data["code"])
        if isinstance(status ,int):
            status = status
        else:
            status = status[1]
        info_data = {"name": device_data["mxlabel"],
                     "code": device_data["code"],
                     "state": self.set_state(status),
                     "local": self.db.get_local(
                         self.model(device_type=self.db.device_type, iot_code=device_data["code"],
                                    sroom_code="")),
                     "update_time": ""}

        self.query_table_data(device_data, info_data)
        return info_data

    def query_table_data(self, device_data, info_data):
        """
        获取 监测点数据
        @param device_data:
        @param info_data:
        @return:
        """
        # 当前的模板
        current_temp = self.ac_temp.get(device_data["mxdevicetype"].rsplit("\\", 1)[1])
        if current_temp is None:
            return "设备模板不存在"
        # {1:"蓝色,未知",2:"红色,告警",3:"绿色,正常"}
        info_data["map_info"] = {"compressor": 1, "evaporator": 1, "condenser": 1}

        monitor_data_dict = {}
        for monitor_key, monitor_value in device_data["sub_monitor"].items():

            monitor_table_data = self.db.query_monitor_table_data(monitor_key)
            if monitor_table_data:
                monitor_data_dict[monitor_key.rsplit(".", 1)[1]] = monitor_table_data

        for temp_key, temp_list in current_temp.items():
            if temp_key == "home_state":
                continue
            print("*" * 100)
            print(temp_key)
            print("*" * 100)
            info_data[temp_key] = []
            for temp_value in temp_list:

                monitor_data = monitor_data_dict.get("%s_" % temp_value["plugin"])

                if not monitor_data:
                    continue
                if temp_key == "parts_info":
                    self.state_judge(info_data, temp_value, monitor_data)
                # 遍历字段
                if info_data["update_time"] < time.strftime("%Y-%m-%d %H:%M:%S",
                                                            time.localtime(monitor_data["_CREATETIME_"])):
                    info_data["update_time"] = time.strftime("%Y-%m-%d %H:%M:%S",
                                                             time.localtime(monitor_data["_CREATETIME_"]))

                info_data[temp_key].append({"phase": temp_value["mxlabel"],
                                            "data": monitor_data[temp_value["key"]],
                                            "unit": temp_value["mxunit"],
                                            "state": monitor_data["State"]})

    def state_judge(self, info_data, temp_value, monitor_data):
        """
        判断 部件状态
        @param info_data:
        @param temp_value:
        @param monitor_data:
        @return:
        """
        if re.search("压缩机", temp_value["mxlabel"]):
            info_data["map_info"]["compressor"] = 2 if info_data["map_info"][
                                                           "compressor"] == 2 else self.state(
                monitor_data["State"])
        if re.search("蒸发器", temp_value["mxlabel"]):
            info_data["map_info"]["evaporator"] = 2 if info_data["map_info"][
                                                           "evaporator"] == 2 else self.state(monitor_data["State"])
        if re.search("冷凝器", temp_value["mxlabel"]):
            info_data["map_info"]["condenser"] = 2 if info_data["map_info"][
                                                          "condenser"] == 2 else self.state(monitor_data["State"])

    @staticmethod
    def state(ac_status):
        """
        配置 部件状态
        @param ac_status:
        @return:
        """
        if ac_status in (2, 3, 4):
            return 2
        if ac_status in (0, 5):
            return 1
        else:
            return 3
